package com.zhao.task.controller;

import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.zhao.task.service.ServerStartedRunner;
import com.zhao.task.service.TaskService;

import lombok.extern.slf4j.Slf4j;

/**
 * 轮询接口
 *
 * @author zhao
 * @date 2018-11-09
 */
@Slf4j
@RestController
@RequestMapping("/task-service")
public class TaskController {

	/**
	 * 启动全部任务
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@GetMapping("/start")
	public String start() {
		Map<String, TaskService> map = ServerStartedRunner.taskServiceMap;
		if (map == null || map.isEmpty()) {
			return "尚未配置进行轮询任务配置";
		}
		for (Entry<String, TaskService> entry : map.entrySet()) {
			TaskService service=entry.getValue();
			try {
				service.start();
			} catch (Exception e) {
				log.error(e.getMessage());
			}
		}
		return "SUCCESS";
	}

	/**
	 * 启动任务
	 * 
	 * @param key 轮询任务key值
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@GetMapping("/start/{key}")
	public String start(@PathVariable("key") String key) {
		TaskService service = ServerStartedRunner.taskServiceMap.get(key);
		if (Objects.isNull(service)) {
			return "key值有误";
		}
		try {
			service.start();
			return "SUCCESS";
		} catch (Exception e) {
			return e.getMessage();
		}
	}
	
	/**
	 * 停止全部任务
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@GetMapping("/stop")
	public String stop() {
		Map<String, TaskService> map = ServerStartedRunner.taskServiceMap;
		if (map == null || map.isEmpty()) {
			return "尚未配置进行轮询任务配置";
		}
		for (Entry<String, TaskService> entry : map.entrySet()) {
			TaskService service=entry.getValue();
			try {
				service.stop();
			} catch (Exception e) {
				log.error(e.getMessage());
			}
		}
		return "SUCCESS";
	}
	
	/**
	 * 停止任务
	 * 
	 * @param key 轮询任务key值
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	@GetMapping("/stop/{key}")
	public String stop(@PathVariable("key") String key) {
		TaskService service = ServerStartedRunner.taskServiceMap.get(key);
		if (Objects.isNull(service)) {
			return "key值有误";
		}
		try {
			service.stop();
			return "SUCCESS";
		} catch (Exception e) {
			return e.getMessage();
		}
	}
}
